{{ $link := .Destination }}
{{ $isRemote := hasPrefix $link "http" }}
{{ $openInTab := $isRemote }}

{{ if not $isRemote }}

  {{ $url := urls.Parse $link }}
  {{ if $url.Path }}

    {{ $link_valid := false }}

    {{/*
      Links to internal pages can be easily found using the .Page.GetPage command.
    */}}
    {{ with .Page.GetPage $url.Path }}
      {{ $fragment := "" }}
      {{ with $url.Fragment }}{{ $fragment = printf "#%s" . }}{{ end }}
      {{ $link = printf "%s%s" .RelPermalink $fragment }}
      {{ $link_valid = true }}
    {{ end }}

    {{/*
      It is currently not possible to resolver resources using .Page.Resources.GetMatch.
      Therefore, we use fileExists to check relative and absolute links to resources
    */}}
    {{ if not $link_valid }}
      {{ if hasPrefix $link "/" }}{{/* absolute file links*/}}
        {{ if fileExists $link }}
          {{ with .Page.GetPage "/" }}
            {{ $link = printf "%s%s" .RelPermalink (substr $link 1) }}
            {{ $link_valid = true }}
            {{ $openInTab = true }}
          {{ end }}
        {{ end }}
      {{ else }}{{/* relative file links*/}}
        {{ with .Page.GetPage "." }}
          {{ if fileExists (printf "%s%s" .File.Dir $link) }}
            {{ $link = printf "%s%s" .RelPermalink $link }}
            {{ $link_valid = true }}
            {{ $openInTab = true }}
          {{ end }}
        {{ end }}
      {{ end }}
    {{ end }}

    {{ if not $link_valid }}
      {{ errorf "in '%s': Could not resolve link '%s'. The linked page or resource does not exist." .Page.File.Path $link }}
    {{ end }}
  {{ end }}
{{ end }}
<a href="{{- $link | safeURL -}}"{{ with .Title}} title="{{- . | safeHTMLAttr -}}"{{ end }}{{ if $openInTab }} target="_blank" rel="noopener"{{ end }}>{{ .Text | safeHTML }}</a>{{- "" -}}
